package com.lizemin.autoconfigure;

import com.lizemin.jdbc.DataSourceProperties;
import com.lizemin.jdbc.PowerJdbcTemplate;
import com.mysql.cj.jdbc.MysqlDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;


/**
 * @author lzm
 * @date 2025/5/13 21:21
 * @description
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({DataSource.class, PowerJdbcTemplate.class})
@EnableConfigurationProperties(DataSourceProperties.class)
public class JdbcAutoConfiguration {

    @Autowired
    DataSourceProperties dataSourceProperties;

    @Bean
    public DataSource mysqlDataSource() {
        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setUser(dataSourceProperties.getUser());
        dataSource.setPassword(dataSourceProperties.getPassword());
        dataSource.setServerName(dataSourceProperties.getHostname());
        dataSource.setPort(Integer.parseInt(dataSourceProperties.getPort()));
        dataSource.setDatabaseName(dataSourceProperties.getDatabaseName());
        dataSource.setUrl("jdbc:mysql://" + dataSourceProperties.getHostname() + ":" + dataSourceProperties.getPort() + "/" + dataSourceProperties.getDatabaseName() + "?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false");
        return dataSource;
    }

    /**
     * 当项目中没有JdbcTemplate的bean时，创建一个JdbcTemplate的bean
     * 这样做是为了允许开发者使用他的配置来覆盖我这里的默认配置
     */
    @ConditionalOnMissingBean(PowerJdbcTemplate.class)
    @Bean
    public PowerJdbcTemplate powerJdbcTemplate(DataSource dataSource) {
        PowerJdbcTemplate jdbcTemplate = new PowerJdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }


}
